package com.jack.leetcode.eachProblem07;

import java.util.LinkedList;

public class 矩阵中的最长递增路径 {

    public static void main(String[] args) {
        int[][] matrix = {{9, 9, 4}, {6, 6, 8}, {2, 1, 1}};
        System.out.println(longestIncreasingPath(matrix));
    }

    public static int longestIncreasingPath(int[][] matrix) {

        int m = matrix.length;
        if (m == 0) {
            return 0;
        }
        int n = matrix[0].length;
        int[][] d = new int[m][n];
        int[][] direct = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                for (int[] dir : direct) {
                    if (isValid(matrix, i + dir[0], j + dir[1]) && matrix[i + dir[0]][j + dir[1]] < matrix[i][j]) {
                        d[i][j]++;
                    }
                }
            }
        }

        LinkedList<int[]> queue = new LinkedList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (d[i][j] == 0) {
                    queue.offer(new int[]{i, j});
                }
            }
        }
        int result = 0;
        while (!queue.isEmpty()) {
            result++;
            for (int i = queue.size(); i > 0; i--) {
                int[] poll = queue.poll();
                for (int[] dir : direct) {
                    if (isValid(matrix, poll[0] + dir[0], poll[1] + dir[1]) && matrix[poll[0] + dir[0]][poll[1] + dir[1]] > matrix[poll[0]][poll[1]]) {
                        if (--d[poll[0] + dir[0]][poll[1] + dir[1]] == 0) {
                            queue.offer(new int[]{poll[0] + dir[0], poll[1] + dir[1]});
                        }
                    }
                }
            }
        }
        return result;
    }

    private static boolean isValid(int[][] matrix, int i, int j) {
        return i >= 0 && j >= 0 && i < matrix.length && j < matrix[0].length;
    }
}
